import React, { useEffect } from 'react';
import { FlatList, View, Text, Image, StyleSheet } from 'react-native';
import { connect, ConnectedProps } from 'react-redux';
import { RootState } from '@/models/index';
import { ISubscription } from '@/models/subscription';

const mapStateToProps = ({ subscription, loading }: RootState) => ({
    list: subscription.subscriptionList,
    loading: loading.effects['subscription/fetchList'] || false,
});

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState { }

function Subscription(props: IProps) {
    const { list, loading, dispatch } = props;
    const onRefresh = () => {
        dispatch({
            type: 'subscription/fetchList',
        });
    };
    const renderItem = ({ item }: { item: ISubscription }) => {
        return <View style={styles.item}>
            <Image source={{ uri: item.image }} style={styles.image} />
            <Text>{item.title}</Text>
        </View>
    }

    useEffect(() => {
        dispatch({
            type: 'subscription/fetchList',
        });
    }, [])
    return <FlatList
        onRefresh={onRefresh}
        refreshing={loading}
        data={list}
        renderItem={renderItem}
        keyExtractor={item => item.id}
    />
}
const styles = StyleSheet.create({
    item: {
        padding: 10,
        flexDirection: 'row',
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderColor: '#ccc',
        alignItems: 'center',
    },
    image: {
        width: 24,
        height: 24,
        marginRight: 10,
    },
});

export default connector(Subscription);